package trie;

import java.util.HashMap;

public class Trie<V> {
	
	private int size;
	private Node<V> root;
	
	public int size() {
		return size;
	}
	
	public boolean isEmpty() {
		return size == 0;
	}
	
	public void clear() {
		size = 0;
		root = null;
	}
	
	public V get(String key) {
		Node<V> node = node(key);
		return node != null && node.word ? node.value : null;
	}
	
	public boolean contains(String key) {
		Node<V> node = node(key);
		return node != null && node.word;
	}
	
	public V add(String key, V value) {
		keyCheck(key);
		if (root == null) {
			root = new Node<>(null);
		}
		Node<V> node = root;
		int len = key.length();
		for (int i = 0; i < len; i++) {
			char c = key.charAt(i);
			node.children = node.children == null ? new HashMap<>() : node.children;
			Node<V> childNode = node.children.get(c);
			if (childNode == null) {
				childNode = new Node<>(node);
				childNode.character = c;
				node.children.put(c, childNode);
			}
			node = childNode;
		}
		
		if (node.word) {	// 已经存在此关键词, 覆盖
			V oldValue = node.value;
			node.value = value;
			return oldValue;
		}
		// 此关键词不存在
		node.value = value;
		node.word = true;
		size++;
		return null;
	}
	
	public V remove(String key) {
		Node<V> node = node(key);
		if (node == null || !node.word) return null;
		size--;
		V oldValue = node.value;
		if (node.children != null && !node.children.isEmpty()) {
			node.word = false;
			return oldValue;
		}
		Node<V> parent = null;
		while ((parent = node.parent) != null) {
			parent.children.remove(node.character);
			if (parent.word || !parent.children.isEmpty()) break;
			node = parent;
		}
		return oldValue;
	}
	
	public boolean startsWith(String prefix) {
		return node(prefix) != null;
	}
	
	private Node<V> node(String key) {
		keyCheck(key);
		Node<V> node = root;
		int len = key.length();
		for (int i = 0; i < len; i++) {
			if (node == null || node.children == null || node.children.isEmpty()) return null;
			char c = key.charAt(i);
			Node<V> childNode = node.children.get(c);
			node = childNode;
		}
		return node;
	}
	
	private void keyCheck(String key) {
		if (key == null || key.length() == 0) throw new IllegalArgumentException("Key must not be null");
	}
	
	private static class Node<V> {
		HashMap<Character, Node<V>> children;
		Node<V> parent;
		Character character;
		V value;
		boolean word;
		public Node(Node<V> parent) {
			this.parent = parent;
		}
		
		
	}
}
